package com.cntaiping.workutil.report2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtils {
    private static final Logger logger = LoggerFactory.getLogger(CsvUtils.class);

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = "\n";

    public static List<String[]> readCsvByBufferedReader(String filePath){
        File csv = new File(filePath);
        BufferedReader br = null;
        List<String[]> records = new ArrayList<>();
        String line = null;
        try {
            if(!csv.exists()){
                logger.error("{} doesn't exist",filePath);
                return null;
            }

            br = new BufferedReader(new InputStreamReader(new FileInputStream(csv), StandardCharsets.UTF_8));
            while ((line = br.readLine() )!= null){
                String[] split = line.split(",");
                records.add(split);
            }
        }catch (Exception e){
            logger.error("read analysis CSV file failed:{}",e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("read analysis CSV file failed");
        }
        return records;

    }
    public static List<String[]> readCsvByStream(InputStream inputStream){
        BufferedReader br = null;
        List<String[]> records = new ArrayList<>();
        String line = null;
        try {
            br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            while ((line = br.readLine() )!= null){
                String[] split = line.split(",");
                records.add(split);
            }
        }catch (Exception e){
            logger.error("读取csv文件失败:{}",e.getMessage());
            e.printStackTrace();
        }
        return records;

    }

    public static <T> List<Map<String, Object>> parseEntityToMap(List<T> dataList) {
        List<Map<String, Object>> dataListMap = new ArrayList<Map<String, Object>>();
        try {
            for (T vo : dataList) {
                Map<String, Object> map = new HashMap<>();

                Field[] fields = vo.getClass().getDeclaredFields();

                for (int i = 0; i < fields.length; i++) {
                    Field f = fields[i];
                    f.setAccessible(true);
                    map.put(f.getName(), f.get(vo));
                }
                dataListMap.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataListMap;

    }

    public static String doExport(List<Map<String, Object>> dataList, String titles, String keys) throws IOException {

        //保证线程安全
        StringBuffer buffer = new StringBuffer();

        String[] titleArr = null;
        String[] keyArr = null;

        titleArr = titles.split(",");
        keyArr = keys.split(",");

        //组装表头
        for (String title : titleArr) {
            buffer.append(title).append(CSV_COLUMN_SEPARATOR);
        }
        buffer.append(CSV_ROW_SEPARATOR);

        //组装数据
        if (dataList.size()>0) {
            for (Map<String, Object> data : dataList) {
                for (String key : keyArr) {
                    buffer.append(data.get(key) == null ? "" : data.get(key)).append(CSV_COLUMN_SEPARATOR);
                }
                buffer.append(CSV_ROW_SEPARATOR);
            }
        }

        return buffer.toString();

    }

}
